package com.basic.tools.codegen.controller;

import com.basic.tools.codegen.common.Action;
import com.basic.tools.codegen.common.Result;
import com.basic.tools.codegen.entity.RequstEntity;
import com.basic.tools.codegen.entity.TemplateGroup;
import com.basic.tools.codegen.service.TemplateGroupService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @date Date : 2020-12-15 9:51
 */
@RestController
@RequestMapping("group")
@Api(tags = "模板组管理")
public class TemplateGroupController {

    @Autowired
    private TemplateGroupService templateGroupService;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    @PostMapping("list")
    public Result listAll(@RequestBody RequstEntity requstEntity) {
        String keyWord = requstEntity.getKeyWord();
        List<TemplateGroup> templateGroups = templateGroupService.listAll();
        if (StringUtils.isNotBlank(keyWord)) {
            templateGroups = templateGroups.stream().filter(tg -> tg.getGroupName().indexOf(keyWord) != -1).collect(Collectors.toList());
        }
        return Action.ok(templateGroups);
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    @GetMapping("get/{id}")
    public Result get(@PathVariable("id") int id) {
        TemplateGroup group = templateGroupService.getById(id);
        return Action.ok(group);
    }

    /**
     * 新增，忽略null字段
     *
     * @param templateGroup 新增的记录
     * @return 返回影响行数
     */
    @PostMapping("add")
    public Result insert(@RequestBody TemplateGroup templateGroup) {
        templateGroupService.insertIgnoreNull(templateGroup);
        return Action.ok(templateGroup);
    }

    /**
     * 修改，忽略null字段
     *
     * @param templateGroup 修改的记录
     * @return 返回影响行数
     */
    @PutMapping("update")
    public Result update(@RequestBody TemplateGroup templateGroup) {
        System.out.println(templateGroup);
        templateGroupService.updateIgnoreNull(templateGroup);
        return Action.ok();
    }

    /**
     * 删除记录
     *
     * @return 返回影响行数
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Integer id) {
        TemplateGroup templateGroup = new TemplateGroup();
        templateGroup.setId(id);
        templateGroupService.deleteGroup(templateGroup);
        return Action.ok();
    }

}